<!-- 游戏工程母包编辑弹窗 -->
<template>
  <el-dialog
    :title="isUpdate ? '修改工程母包' : '添加工程母包'"
    :visible="visible"
    width="1000px"
    :destroy-on-close="true"
    :lock-scroll="false"
    @update:visible="updateVisible"
    append-to-body
    :close-on-click-modal="false"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="文件路径:" prop="file_url">
        <el-upload
          accept=".apk"
          class="upload-demo"
          :action="uploadImgUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :limit="1"
          :headers="myHeaders"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :http-request="uploadChunk"
        >
          <div>
            <el-button size="small" type="primary">点击上传</el-button>
            <div>文件上传（仅支持.apk 格式）</div>
          </div>
        </el-upload> 
        <!-- 添加进度条 -->
        <el-progress v-if="showProgress" :percentage="uploadProgress" />
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading"
        >保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import setting from "@/config/setting";
import md5 from "js-md5"; //引入MD5加密

export default {
  name: "gameEngineeringEdit",
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
    gameEditID: Number,
    gameID: String,
  },
  components: {},
  data() {
    let token = setting.takeToken();
    return {
      // 表单数据
      gameAll: [],
      fileList: [],
      sdk_version: "origin",
      uploadImgUrl:
        process.env.VUE_APP_API_BASE_URL +
        "/upload/zoneUpload?sdk_version=origin",
      form: Object.assign({}, this.data),
      myHeaders: { Authorization: token },
      // 表单验证规则
      rules: {
        file_url: [{ required: true, message: "请上传文件", trigger: "blur" }],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      currentChunk: 0, // 当前分片数
      showProgress: false, // 是否显示进度条
      uploadProgress: 0 // 上传进度
    };
  },
  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        console.log(this.form, "xiugai1");
        this.isUpdate = true;
        this.showProgress = false;
        this.uploadProgress = 0;
      } else {
        this.form = {};
        this.showProgress = false;
        this.uploadProgress = 0;
        this.isUpdate = false;
      }
    },

    fileList: {
      handler(val) {
        if (val.length) {
          this.$set(this.form, "path", val[0].save_name);
          // this.$set(this.form, "file_size", val[0].file_size);
          // this.$set(this.form, "game_id", val[0].game_id);
        } else {
          this.$set(this.form, "path", "");
          // this.$set(this.form, "file_size", "");
          // this.$set(this.form, "game_id", "");
        }
      },
      deep: true
    }
  },
  methods: {
    handleRemove() {
      this.fileList = [];
    },
    handlePreview(file) {
      console.log(file);
    },
    successUpload(response) {
      console.log(response);
    },
    handleExceed() {
      this.$message.warning(`当前限制选择 1 个文件`);
    },
    async beforeRemove(file) {
      try {
        await this.$confirm(`确定移除 ${file.name}？`);
        // 用户点击确定后执行的代码
        this.showProgress = false;
        this.uploadProgress = 0;

        this.rules.file_url = [
          { required: true, message: "请上传文件", trigger: "blur" }
        ];
        this.uploadChunk("false");
      } catch (error) {
        // 用户点击取消或关闭对话框时执行的代码，这里不需要做任何操作
      }
    },
    // 分片上传文件
    async uploadChunk(file) {
      console.log(file, "file");
      if (file == "false") {
        window.location.reload();
        return;
      } else if (file == "none") {
        return;
      }
      const totalSize = file.file.size;
      const totalSizeInMegabytes = totalSize / (1024 * 1024);
      // file_size
      const totalSizeInMegabytesFixed = totalSizeInMegabytes.toFixed(2) + "MB";

      const chunkSize = 10 * 1024 * 1024; // 10MB
      const chunkCount = Math.ceil(totalSize / chunkSize);
      console.log(
        chunkCount,
        "chunkCount",
        "totalSize",
        totalSizeInMegabytesFixed,
        "chunkSize",
        chunkSize
      );

      // 显示进度条
      this.showProgress = true;
      this.uploadProgress = 0;
      const readChunkMD5 = async chunk => {
        return new Promise(resolve => {
          let fileReaderInstance = new FileReader();
          fileReaderInstance.readAsBinaryString(chunk);
          fileReaderInstance.addEventListener("load", e => {
            let fileBlob = e.target.result;
            let chunkMD5 = md5(fileBlob);
            resolve(chunkMD5);
          });
        });
      };

      const uploadChunkRecursive = async index => {
        if (index >= chunkCount) {
          return;
        }
        // 更新当前分片数和总分片数
        this.currentChunk = index + 1;

        const start = index * chunkSize;
        const end = Math.min(start + chunkSize, totalSize);
        const chunk = file.file.slice(start, end);

        const chunkMD5 = await readChunkMD5(chunk);

        const formData = new FormData();
        // const Sdk_version = this.isUpdate
        //   ? this.form.file_type
        //   : this.sdk_version;
        formData.append("file", chunk);
        formData.append("chunkNumber", index + 1);
        formData.append("chunkSize", chunkSize);
        formData.append("currentChunkSize", chunk.size);
        formData.append("filename", file.file.name);
        formData.append("totalChunks", chunkCount);
        formData.append("md5", chunkMD5);
        console.log("mmmmd", chunkMD5);

        try {
          const res = await this.$http.post(
            "/upload/zoneUpload?sdk_version=origin",
            formData
          );
          console.log(res);
          if (res.data.code === 2) {
            this.rules.file_url = [
              { required: false, message: "请上传文件", trigger: "blur" }
            ];
            this.uploadProgress = Math.round(
              (this.currentChunk / chunkCount) * 100
            );
            this.$set(this.form, "path", res.data.file_path);
            // this.$set(this.form, "file_size", totalSizeInMegabytesFixed);
            // this.$set(this.form, "game_id", file.file.name);
            console.log(this.form);
            this.$message.success(res.data.msg);
          } else if (res.data.code === 1) {
            this.uploadProgress = Math.round(
              (this.currentChunk / chunkCount) * 100
            );
            await uploadChunkRecursive(index + 1);
          }
        } catch (e) {
          this.loading = false;
          this.$message.error(e.message);
        }
      };

      await uploadChunkRecursive(0);
    },
    /* 保存编辑 */
    save() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          
          this.form.game_id = this.gameID;
          if (this.isUpdate) {
            this.form.package_id = this.gameEditID;
          }
          const saveForm = {}
          this.$set(saveForm, "path", this.form.path);
          this.$set(saveForm, "id", this.form.id);
          this.$set(saveForm, "game_id", this.form.game_id);
          console.log(this.form,saveForm, "item");
            this.$http
              .post("/Gameorigin/edit", saveForm)
              .then(res => {
                this.loading = false;
                if (res.data.code === 0) {
                  this.$message.success(res.data.msg);
                  if (!this.isUpdate) {
                    this.form = {};
                  }
                  this.rules.file_url = [
                    { required: true, message: "请上传文件", trigger: "blur" }
                  ];
                  this.showProgress = false;
                  this.uploadProgress = 0;
                  this.updateVisible(false);
                  this.$emit("done");
                } else {
                  this.$message.error(res.data.msg);
                }
              })
              .catch(e => {
                this.loading = false;
                this.$message.error(e.message);
              });
          } else {
            return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit("update:visible", value);
      console.log(this.fileList, "fflst");
      if (this.showProgress) {
        this.uploadChunk("false");
      }
      this.showProgress = false;
      this.uploadProgress = 0;
    },
    // 是否更改了
    remoteMethod(query) {
      // console.log("！！！");
      if (query !== "") {
        this.loading = true;
      } else {
        // console.log("！！!!！");
      }
    }
  }
};
</script>

<style scoped>
::v-deep .el-upload {
  text-align: left;
}
</style>
